package com.marveal.rabbit.common.convert;

import com.marveal.rabbit.common.serializer.Serializer;
import com.marveal.rabbit.common.util.Assert;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

public class GenericMessageConverter implements MessageConverter {

    private final Serializer serializer;

    public GenericMessageConverter(Serializer serializer) {
        Assert.notNull(serializer, "#GenericMessageConverter.genericMessageConverter# serializer is null");
        this.serializer = serializer;
    }

    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        com.marveal.rabbit.api.Message message = (com.marveal.rabbit.api.Message) o;
        message.setDelayMills(message.getDelayMills());
        return new Message(serializer.serializeRaw(message), messageProperties);
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        byte[] messageBody = message.getBody();
        return serializer.deserializer(messageBody);
    }
}
